package jp.shuitic.hatebwebhook.twitter.web.server;

import java.util.ArrayList;
import java.util.logging.Logger;

import jp.shuitic.hatebwebhook.twitter.web.client.HatebTwitService;
import jp.shuitic.hatebwebhook.twitter.web.client.HatebWebHookTwitUser;
import jp.shuitic.hatebwebhook.twitter.web.client.HatebWebHookTwitException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * GWTから呼び出されるHatebWebHookTwitUserを操作するサービスの実装
 * @author shuitic
 */
@SuppressWarnings("serial")
public class HatebTwitServiceImpl extends RemoteServiceServlet implements
		HatebTwitService {
	
	static private UserService userService = null;
	static {
		userService = UserServiceFactory.getUserService();
	}

	static private Logger logger = Logger.getLogger("jp.shuitic");
	
	@Override
	public boolean removeHatebHookTwitUser() throws HatebWebHookTwitException {
		logger.info("remove");
		User user = getCurrentUser();
		HatebWebHookTwitUserService hwhtService = new HatebWebHookTwitUserServiceImpl(user);
		return hwhtService.removeCurrentUser();
	}

	@Override
	public HatebWebHookTwitUser updateHatebHookTwitUser(String hatebUserName,
			String hatebWebHookKey, String twitterUserName,
			String twitterPassword) throws HatebWebHookTwitException {

		logger.info("update");
		User user = getCurrentUser();
		HatebWebHookTwitUserService hwhtService = new HatebWebHookTwitUserServiceImpl(user);
		try {
			HatebWebHookTwitUser hwtUser = hwhtService.validate(hatebUserName, hatebWebHookKey, twitterUserName, twitterPassword);
			hwhtService.save(hwtUser);
			return hwtUser;
		} catch (HatebWebHookTwitException hwhte) {
			throw hwhte;
		} catch (Exception e) {
			ArrayList<String> msg = new ArrayList<String>();
			msg.add(e.getMessage());
			throw new HatebWebHookTwitException(msg);
		}
	}

	@Override
	public HatebWebHookTwitUser getHatebHookTwitUser()
			throws HatebWebHookTwitException {
		logger.info("find");
		User user = getCurrentUser();
		HatebWebHookTwitUserService hwhtService = new HatebWebHookTwitUserServiceImpl(user);
		HatebWebHookTwitUser hwtUser = hwhtService.findByCurrentUser();
		return hwtUser;
	}

	
	private static User getCurrentUser() throws HatebWebHookTwitException {
		User user = userService.getCurrentUser();
		if (user == null) {
			logger.info("not login");
			ArrayList<String> msg = new ArrayList<String>();
			msg.add("ログインしていません");
			throw new HatebWebHookTwitException(msg);
		}
		return user;
	}
	
}
